
import IComponent from "./IComponent";
import SingleObjectPool from "../objectPool/SingleObjectPool";
import EntityWorld from "./EntityWorld";

export enum EntityLifeState {
    Die = 0,
    Live = 1,
}

export default class Entity {

    public static ObjectPool: SingleObjectPool = new SingleObjectPool(
        () => new Entity(),
        (entity) => {
            let e = entity as Entity;
            e.isActive = true;
            e.lifeState = EntityLifeState.Live;
        },
        (entity) => {
            let e: Entity = entity as Entity;
            e.id = "";
            e.isActive = false;
            e.lifeState = EntityLifeState.Die;
        }
    );

    lifeState: EntityLifeState = EntityLifeState.Live;
    isActive: boolean = true;
    id: string = null;
    world: EntityWorld = null;

    Entity(id: string) {
        this.id = id;
    }

    ContainComponent(component: IComponent): boolean {
        if (!this.isActive) return false;
        return this.world.GetComponentByEntityId(this.id, component.GetType()) !== null;
    }

    public AddComponent(component: IComponent): Entity {
        if (!this.ContainComponent(component)) {
            component.entityId = this.id;
            this.world.AddComponent(component);
        }
        return this;
    }

    GetComponent(type: string): IComponent {
        if (!this.isActive) return null;
        return this.world.GetComponentByEntityId(this.id, type);
    }

    RemoveComponent(component: IComponent): void {
        if (this.ContainComponent(component)) {
            this.world.RemoveComponent(component);
            component.entityId = null;
        }
    }
}